package com.realshare.frame.util.safety.america;

import com.realshare.frame.util.StringUtils;
import com.realshare.frame.util.safety.Base64Utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by 曹传喜 on 2016/10/27.
 * SHA 单向加密
 */

public class SHAUtils {
    private static final String ALGORITHM = "SHA";

    public static String encrypt(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
            return Base64Utils.encoder(messageDigest.digest(data.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 返回SHA单向加密后的十六进制字符串
     *
     * @param data 需要处理的数据
     * @return 返回字符串
     */
    public static String getEncryptForHex(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
            byte[] digestData = messageDigest.digest(data.getBytes());
            return StringUtils.parseByteArray2HexStr(digestData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        Date date = new Date();
        String source = "一醉汉不慎从三楼掉下，引来路人围观，一警察过来：发生了什么事？醉汉：不清楚，我也是刚到！";
        System.out.println("原文字：" + source);
        System.out.println("sha加密后：" + encrypt(source));
        System.out.println("sha单向加密后的十六进制字符串：" + getEncryptForHex(source));
        System.out.println("加密耗时：" + (new Date().getTime() - date.getTime()) + "毫秒");
    }
}
